package com.cim120.commons.cip.process.impl;

import com.cim120.commons.cip.constant.ImageEnum;
import com.cim120.commons.cip.model.Image;
import com.cim120.commons.cip.process.ImageProcess;
import com.cim120.commons.cip.process.strategy.CropStrategy;
import com.cim120.commons.cip.process.strategy.HmpPortraitCropStrategy;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Collections;
import java.util.Map;

/**
 * Created by tonydeng on 16/4/27.
 */
public class ImageProcessImpl implements ImageProcess {
    private static final Logger log = LoggerFactory.getLogger(ImageProcessImpl.class);
    private static Map<String, CropStrategy> cropStrategyMap;

    @Override
    public Map<String, Image> cropImageByFile(ImageEnum.Project project, ImageEnum.Type type, File image) {
        if (project != null && type != null && image != null && image.exists()) {
            //对原始图片进行处理
            image = this.qualitry(image);
            //根据图片配置来切图
            CropStrategy cs = getCropStrategy(project.name(), type.name());
            if (cs != null) {
                boolean corpStatus = cs.crop(type, Lists.newArrayList(image));
                if (!corpStatus) {
                    if (log.isErrorEnabled())
                        log.error("corp Image error:'" + project.name() + "'  '" + type.name() + "'");
                    return null;
                }
                Map<String, Image> results = Maps.newHashMap();
                Image im = new Image();
                im.setFile(image);
                results.put(ImageEnum.Flag.ORIGIN.getValue(), im);
                //构建返回map对象
                return cs.getResultMap(type, results);
            }
        }

        return Collections.EMPTY_MAP;
    }

    private CropStrategy getCropStrategy(String project, String type) {
        return initCropStrategyMap().get(project + "-" + type);
    }

    private Map<String, CropStrategy> initCropStrategyMap() {
        if (cropStrategyMap == null) {
            cropStrategyMap = Maps.newConcurrentMap();
            cropStrategyMap.put(ImageEnum.Project.hmp.name() + "-" + ImageEnum.Type.hmp_portrait.name(), new HmpPortraitCropStrategy());
        }
        return cropStrategyMap;
    }
}
